const jwt = require('jsonwebtoken')
const { JWT_SECERT } = require('../config/config.default')
const {success, text} = require("../constant");
const auth = async (ctx, next) => {
    try {
        const { authorization, token } = ctx.request.header
        console.log('authorization', ctx.request.header)
        console.log('body', ctx.request.body)
        console.log('ctx', ctx)
        // const token = authorization.replace('Bearer ', '')
        let tk = null
        if (token) {
            tk = token
        } else if(authorization) {
            tk = authorization.replace('Bearer ', '')
        }
        ctx.state.user = jwt.verify(tk, JWT_SECERT)
    } catch (err) {
        console.error('token 无效', err.name)
        let errMsg = 'token 无效'
        let code = 1
        switch (err.name) {
            case 'TokenExpiredError':
                errMsg = '登录过期'
                code = 403
                break
            case 'JsonWebTokenError':
                errMsg = 'token 无效'
                break
        }
        // ctx.app.emit('error', {
        //     code: code,
        //     message: errMsg,
        //     result: null
        // }, ctx, 200)
        ctx.body = {
            code: code,
            message: errMsg,
            result: null
        }
        return
    }
    await next()
}
module.exports = {
    auth
}

